package com.rzt.cft.admin.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzt.cft.constant.ServiceStatus;
import com.rzt.cft.admin.controller.BaseController;
import com.rzt.cft.dto.ResponseData;
import com.rzt.cft.dto.sys.SysJobDto;
import com.rzt.cft.dto.sys.SysUserDto;
import com.rzt.cft.entity.sys.SysJob;
import com.rzt.cft.entity.sys.SysUser;
import com.rzt.cft.entity.sys.SysUserJob;
import com.rzt.cft.param.IdParam;
import com.rzt.cft.param.sys.SysUserJobParam;
import com.rzt.cft.param.uc.UserEditPwdParam;
import com.rzt.cft.param.uc.UcUserParam;
import com.rzt.cft.param.uc.UserHeadPortraitParam;
import com.rzt.cft.param.uc.UserResetPwdParam;
import com.rzt.cft.service.sys.ISysJobService;
import com.rzt.cft.service.sys.ISysUserJobService;
import com.rzt.cft.service.sys.ISysUserService;
import com.rzt.cft.utils.CustomUtil;
import com.rzt.cft.utils.ParseWrapper;
import com.rzt.cft.utils.ShiroUtils;
import com.rzt.cft.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 系统-后台用户 前端控制器
 * </p>
 *
 * @author zhongzhong
 * @since 2019-12-31
 */
@RestController
@RequestMapping("/v1/sys-user")
@Api(tags = "系统用户相关接口")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserJobService sysUserJobService;

    @Autowired
    private ISysJobService sysJobService;

    @ApiOperation("系统用户当前用户信息")
//    @RequiresPermissions("sys:user:list")
    @PostMapping("/currentUser")
    public ResponseData<SysUserDto> currentUser() {
        SysUserDto sysUserDto = getUser();
        return success(sysUserDto);
    }

    @ApiOperation("系统用户列表(分页)")
//    @RequiresPermissions("sys:user:list")
    @PostMapping("/list")
    public ResponseData<IPage<SysUserDto>> list(@RequestBody UcUserParam para) {
        Page page = getPage(para);
        QueryWrapper<SysUser> queryWrapper = ParseWrapper.parseWrapper(para);
        IPage<SysUser> pageUser = sysUserService.page(page, queryWrapper);
        return success(pageUser.convert(x -> CustomUtil.maping(x, SysUserDto.class)));
    }

    @ApiOperation("系统用户详情")
//    @RequiresPermissions("sys:user:detail")
    @PostMapping("/detail")
    public ResponseData<SysUserDto> detail(@RequestBody IdParam param) {
        SysUser sysUser = sysUserService.getById(param.getId());
        if (Objects.isNull(sysUser)) {
            return fail(ServiceStatus.PARAM_EXCEPTION);
        }

        SysUserDto userDto = CustomUtil.maping(sysUser, SysUserDto.class);
        QueryWrapper<SysUserJob> queryWrapper = new QueryWrapper();
        queryWrapper.like("user_id", param.getId());
        // 填充岗位信息
        SysUserJob userJob = sysUserJobService.getOne(queryWrapper);
        if (!Objects.isNull(userJob)) {
            SysJob job = sysJobService.getById(userJob.getJobId());
            userDto.setJob(CustomUtil.maping(job, SysJobDto.class));
        }
        return success(userDto);
    }

    @ApiOperation("新增系统用户")
//    @RequiresPermissions("sys:user:add")
    @PostMapping("/add")
    public ResponseData<Boolean> userSave(@RequestBody SysUserDto userDto) {
        ResponseData paramVali = ValidatorUtils.validateEntity(userDto);
        if (Objects.nonNull(paramVali)) {
            return fail(paramVali);
        }
        //判断用户名是否重复
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userDto.getUserName());
        List<SysUser> userList = sysUserService.list(queryWrapper);
        if (userList.size() > 0) {
            return fail(ServiceStatus.REPEAT_OF_USER_NAME);
        }
        //判断手机号是否重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", userDto.getPhone());
        userList = sysUserService.list(queryWrapper);
        if (userList.size() > 0) {
            return fail(ServiceStatus.REPEAT_OF_USER_PHONE);
        }
        //查询岗位是否存在
//        SysJobDto jobDto = userDto.getJob();
//        SysJob sysJob = sysJobService.getById(jobDto.getId());
//        if (Objects.isNull(sysJob)) {
//            return fail(ServiceStatus.POSITION_DOES_NOT_EXIST);
//        }
        Boolean result = sysUserService.addUser(userDto);
        return success(result);
    }

    @ApiOperation("系统用户修改")
//    @RequiresPermissions("sys:user:update")
    @PostMapping("/update")
    public ResponseData<Boolean> update(@RequestBody SysUserDto userDto) {
        SysUser oldUser = sysUserService.getById(userDto.getId());
        if (Objects.isNull(oldUser))
            return fail(ServiceStatus.PARAM_EXCEPTION);
        Boolean result = sysUserService.updateById(CustomUtil.maping(userDto, SysUser.class));
        return success(result);
    }

    @ApiOperation("系统用户删除")
//    @RequiresPermissions("sys:user:delete")
    @PostMapping("/delete")
    public ResponseData<Boolean> delete(@RequestBody String... ids) {
        Boolean result = sysUserService.removeByIds(Arrays.asList(ids));
        return success(result);
    }

    @ApiOperation("系统用户上传头像")
//    @RequiresPermissions("sys:user:updatePwd")
    @PostMapping("/updateHeadPortrait")
    public ResponseData<Boolean> updateHeadPortrait(@RequestBody UserHeadPortraitParam para) {
        // 获取用户信息
        SysUserDto user = getUser();
        if (Objects.isNull(user)) {
            return fail(ServiceStatus.TOKEN_INVALID);
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(user.getId());
        sysUser.setHeadPortrait(para.getHeadPortrait());
        boolean result = sysUserService.updateById(sysUser);
        return success(result);
    }

    @ApiOperation("系统用户修改密码")
//    @RequiresPermissions("sys:user:updatePwd")
    @PostMapping("/userUpdatePwd")
    public ResponseData<Boolean> userUpdatePwd(@RequestBody UserEditPwdParam para) {
        // 获取用户信息
        SysUserDto user = getUser();
        if (Objects.isNull(user)) {
            return fail(ServiceStatus.TOKEN_INVALID);
        }
        String oldPassword = ShiroUtils.sha256(para.getOldPwd(), getUser().getSalt());
        // 验证原密码是否正确
        if (!oldPassword.equals(user.getUserPwd())) {
            return fail(ServiceStatus.OLD_PWD_ERROR);
        }
        String newPassword = ShiroUtils.sha256(para.getNewPwd(), getUser().getSalt());
        SysUser sysUser = new SysUser();
        sysUser.setId(user.getId());
        sysUser.setUserPwd(newPassword);
        boolean result = sysUserService.updateById(sysUser);
        if (result) {
            ShiroUtils.logout();
        }
        return success(result);
    }

    @ApiOperation("系统用户重置密码")
//    @RequiresPermissions("sys:user:resetPwd")
    @PostMapping("/resetPwd")
    public ResponseData<Boolean> resetPwd(@RequestBody UserResetPwdParam para) {
        // 获取用户信息
        SysUser user = sysUserService.getById(para.getId());
        if (Objects.isNull(user)) {
            return fail(ServiceStatus.PARAM_EXCEPTION);
        }

        String newPassword = ShiroUtils.sha256(para.getNewPwd(), user.getSalt());
        user.setUserPwd(newPassword);
        boolean result = sysUserService.updateById(user);
        return success(result);
    }

    @ApiOperation("用户岗位分配")
//    @RequiresPermissions("sys:user:userJobAllot")
    @PostMapping("/userJobAllot")
    public ResponseData<Boolean> userJobAllot(@RequestBody SysUserJobParam param) {
        //校验用户是否存在
        SysUser user = sysUserService.getById(param.getUserId());
        if (Objects.isNull(user)) {
            return fail(ServiceStatus.NO_USER);
        }

        //校验岗位是否存在
        SysJob job = sysJobService.getById(param.getJobId());
        if (Objects.isNull(job)) {
            return fail(ServiceStatus.POSITION_DOES_NOT_EXIST);
        }

        boolean result = sysUserService.allotUserJob(param);
        return success(result);
    }

//    @ApiOperation("根据部门查找系统用户")
////    @RequiresPermissions("sys:user:userByDept")
//    @PostMapping("/userByDept")
//    public ResponseData<SysUserDto> userByDept(@RequestBody Integer deptId) {
//        //TODO
//        return success(null);
//    }

//    @ApiOperation("根据岗位查找系统用户")
////    @RequiresPermissions("sys:user:userByJob")
//    @PostMapping("/userByJob")
//    public ResponseData<SysUserDto> userByJob(@RequestBody Integer jobId) {
//        //TODO
//        return success(null);
//    }
}
